<?php
namespace app\model;

/**
 * Author: cbw
 * Desc: 摇一摇多礼品
 * Time: 2022/3/30 16:24
 * Email: 17854288794@163.com
 */
class YxGifts{
    /**
     * Desc:获取摇一摇礼品
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/3/30 16:26
     * @param $config
     * @param $themeid
     * @param $fans
     */
    public static function getGift($config,$themeid,$fans)
    {
        global $_G;
        //判断摇一摇是否支付
        $themyrecord = Record::getLastGroupByUid($fans['uid'],$themeid);
        if ($config['comm4ispay']==1 && !$themyrecord){//需支付  用户未支付
            return_json(1,'需要付款才能摇一摇');
        }
        //判断总量
        $user_all_flag = count(db_getall(t_yyy_gifts_flag,['uid'=>$fans['uid'],'themeid'=>$themeid]));
        if ($user_all_flag>=$config['comm4sum']){
            return_json(1,'达到摇一摇次数上限');
        }
        //判断今日总量
        $sql = "select count(*) as cnt from ".tablename(t_yyy_gifts_flag).
            " where themeid=$themeid and uid = {$fans['uid']} AND TO_DAYS(created_at) = TO_DAYS(NOW()) ";
        $user_today_flag =  intval(db_find($sql)['cnt']);
        if ($user_today_flag>=$config['comm4daynum']){
            return_json(1,'达到今日摇一摇次数上限');
        }
        $prize_arr = $config['yx_gifts'];
        $temp_prize_arr = [];
        $arr = [];
        foreach ($prize_arr as $key => $val) {
            if ($val['status']!=1){
                $arr[$key] = $val['yx_gift_maxodds'];
                array_push($temp_prize_arr,$val);
            }
        }
        $reponse = ['msg'=>'很遗憾未中奖','code'=>-1];
        $rid = get_rand($arr,$temp_prize_arr); //根据概率获取奖项id
        $res = [];
        if ($rid>0){
            //中奖
            $prize = '';
            foreach ($temp_prize_arr as $key => $val) {
                if ($val['id']==$rid){
                    $prize = $val;
                    break;
                }
            }
            //判断是否存在待发圈记录
            $wait_flag = db_getall(t_yyy_gifts_flag,['uid'=>$fans['uid'],'themeid'=>$themeid,'status'=>1]);
            if ($wait_flag){
                //待发圈记录失效
                $sql = " update ".tablename(t_yyy_gifts_flag)." set status=11 where uid={$fans['uid']} and themeid={$themeid} and status=1";
                $result = db_find($sql);
            }
            //写入数据库
            $insert_data = [
                'uid'=>$fans['uid'],
                'gid'=>$prize['id'],
                'status'=>1,
                'themeid'=>$themeid,
                'created_at'=>date("Y-m-d H:i:s",time()),
                'updated_at'=>date("Y-m-d H:i:s",time())
            ];
            $res = $insertid = db_insert(t_yyy_gifts_flag,$insert_data);
            //config  扣除礼品库存
            foreach ($prize_arr as $kk => $vv){
                if ($vv['id']==$rid){
                    $prize_arr[$kk]['yx_gift_stock'] = $vv['yx_gift_stock']-1;
                    break;
                }
            }
            //重置config
            $config_save = 	Theme::getConfig($themeid,true);
            $config_save['yx_gifts'] = $prize_arr;
            Theme::setConfig($config_save,$themeid,$_G['mpid']);

            $msg = '恭喜您获得'.$prize['yx_gift_name'];
            return_json(0,$msg,['img'=>$prize['yx_gift_img'],'gid'=>$prize['id']]);
        }
        //默认未中奖
        return_json(-1,'很遗憾未中奖');
    }

    /**
     * Desc:收集客资
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/3/30 16:35
     * @param $params
     * @param $fans
     * @param $themeid
     * @return mixed
     */
    public static function updateFanInfo($params,$fans,$themeid)
    {

        $where = ['themeid'=>$themeid,'uid'=>$fans['uid']];
        $edit_data = ['username'=>$params['username'],'mobile'=>$params['mobile']];
        $res = db_update(t_fans,$edit_data,$where);
        if (!$res){
            return_json(1,'资料更新失败，稍后重试');
        }else{
            return_json(0,'操作成功');
        }
    }

    /**
     * Desc:更新用户礼品记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/3/30 17:14
     * @param $where
     * @param $data
     * @return mixed
     */
    public static function editFanGift($where,$data)
    {
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = db_update(t_yyy_gifts_flag,$data,$where);
        return $res;
    }

    /**
     * Desc:获取用户全部礼品记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/3/30 17:21
     * @param $where
     * @return mixed
     */
    public static function getUserAllGifts($where)
    {
        return db_getall(t_yyy_gifts_flag,$where,[],'',['id desc']);
    }

    public static function getGiftsByInfo($themeid,$search_data='',$start_day='',$end_day='',$status=0,$page_start,$page_size)
    {
        $first_condition = " where a.themeid=$themeid";
        if ($status!=0){
            $first_condition = " where a.themeid=$themeid and a.status=$status";
        }

        $last_condition = " order by  a.created_at desc limit ".$page_start.",".$page_size;
        $condition = "";
        if ($search_data){
            $condition .= " AND b.nickname LIKE '".$search_data."'"." or b.mobile LIKE '".$search_data."' "." or b.username LIKE '".$search_data."'";
        }
        if ($start_day && $end_day){
            $condition .= "  and a.created_at between '".date("Y-m-d H:i:s",$start_day)."' and '".date("Y-m-d H:i:s",$end_day)."' ";
        }

        $sql = "select a.*,b.username,b.avatar,b.nickname,b.mobile  from ".tablename(t_yyy_gifts_flag).
            " as a  LEFT JOIN ". tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid ".$first_condition.$condition.$last_condition;
        $list = db_select($sql);
        $sql = "select count(*)  from ".tablename(t_yyy_gifts_flag).
            " as a  LEFT JOIN ". tablename(t_fans)." as b on a.uid=b.uid and a.themeid=b.themeid ".$first_condition.$condition;
        $total = (int)db_fetchcolumn($sql);
        return array('list'=>$list,'total'=>$total);
    }

    /**
     * Desc:格式化产品数组  外键为id
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/3/30 17:57
     * @param $config
     * @return array
     */
    public static function getFormatGifts($config){
        $gifts = $config['yx_gifts'];
        $temp_gifts = [];
        if (!$gifts){
            return [];
        }
        foreach ($gifts as $key => $val){
            $temp_gifts[$val['id']] = $val;
        }
        return $temp_gifts;
    }

    /**
     * Desc:获取选择条件
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/3/30 18:19
     * @return array[]
     */
    public static function getStatusArr($themeid)
    {
        $init_arr =  [
            ['status'=>0,'title'=>'全部','num'=>0],
            ['status'=>1,'title'=>'待发圈','num'=>0],
            ['status'=>11,'title'=>'失效','num'=>0],
            ['status'=>2,'title'=>'待客资','num'=>0],
            ['status'=>3,'title'=>'待兑换','num'=>0],
            ['status'=>4,'title'=>'已核销','num'=>0],
        ];
        foreach ($init_arr as $key => $val){
            $sql = '';
            $sql = " select count(*) as cnt from ".tablename(t_yyy_gifts_flag)." where themeid='$themeid'";
            if ($val['status']!=0){
                $status = $val['status'];
                $sql .= " and status=$status";
            }
            $init_arr[$key]['num'] = db_find($sql)['cnt'];
        }
        return $init_arr;
    }

    /**
     * Desc:查询用户礼品记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/4/1 13:17
     * @param $themeid
     * @param $fans
     * @param $f_id
     * @param $config
     * @return array
     */
    public static function getGiftItem($themeid,$fans,$f_id,$config)
    {
        global $_G,$_P;
        $res = db_get(t_yyy_gifts_flag,['themeid'=>$themeid,'id'=>$f_id,'uid'=>$fans['uid']]);
        if (!$res){
            return [];
        }else{
            $config_gifts = Yxgifts::getFormatGifts($config);
            $info = [
                'username'=>$fans['username'],
                'mobile'=>$fans['mobile'],
                'f_id'=>$res['id'],
                'status'=>$res['status'],
                'gift_title'=>$config_gifts[$res['gid']]['yx_gift_name'],
                'img'=>$config_gifts[$res['gid']]['yx_gift_img'],
                'updated_at'=>$res['updated_at']
            ];
            return $info;
        }
    }
}